import SpecialZoomLevel from "../SpecialZoomLevel";
import getDestination from "../utils/getDestination";
import { PdfJs } from "../interface";
import Annotation from "./Annotation";
import { FC, ReactElement } from "react";

interface LinkProps {
  annotation: PdfJs.Annotation;
  doc: PdfJs.PdfDocument;
  page: PdfJs.Page;
  viewport: PdfJs.ViewPort;
  onExecuteNamedAction(action: string): void;
  onJumpToDest(
    pageIndex: number,
    bottomOffset: number,
    leftOffset: number,
    scaleTo: number | SpecialZoomLevel
  ): void;
}

const Link: FC<LinkProps> = ({
  annotation,
  doc,
  page,
  viewport,
  onExecuteNamedAction,
  onJumpToDest,
}) => {
  const link = (e: MouseEvent): void => {
    e.preventDefault();
    annotation.action
      ? onExecuteNamedAction(annotation.action)
      : getDestination(doc, annotation.dest).then((target) => {
          const { pageIndex, bottomOffset, scaleTo } = target;
          onJumpToDest(
            bottomOffset ? pageIndex + 1 : pageIndex,
            bottomOffset,
            0,
            scaleTo
          );
        });
  };

  const isRenderable = !!(
    annotation.url ||
    annotation.dest ||
    annotation.action
  );
  const attrs = annotation.url
    ? {
        href: annotation.url,
        rel: "noopener noreferrer nofollow",
        target: annotation.newWindow ? "_blank" : "",
        title: annotation.url,
      }
    : {
        href: "",
        onClick: link,
      };

  return (
    <Annotation
      annotation={annotation}
      hasPopup={false}
      ignoreBorder={false}
      isRenderable={isRenderable}
      page={page}
      viewport={viewport}
    >
      {(props): ReactElement => (
        <div
          {...props.slot.attrs}
          className="rpv-core__annotation rpv-core__annotation--link"
          data-annotation-id={annotation.id}
        >
          <a {...attrs} />
        </div>
      )}
    </Annotation>
  );
};

export default Link;
